import {createRouter, createWebHashHistory, RouteRecordRaw} from "vue-router"
import routerList from '@/router/index.ts'
import token from "@/frame/apis/token/token.ts"
import {processRequest} from "@/frame/apis/request"
import {FRAME_APIS} from "@/frame/apis/contact"

const routes: RouteRecordRaw[] = [
    {
        path: "/",
        redirect: "/login"
    },
    {
        path: "/login",
        name: "login",
        component: () => import("@/frame/pages/login/index.vue"),
        meta: {
            title: "登录"
        }
    },
    {
        path: "/index",
        name: "index",
        component: () => import("@/frame/pages/index/index.vue"),
        meta: {
            title: "首页"
        },
        redirect: "/code-rule",
        children: routerList
    }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes: routes
})

router.beforeEach(async (to, from, next) => {
    //登录页不鉴权
    if (to.name === "login") {
        next()
        return
    }
    const tokenValue = token.get()
    if (tokenValue) {
        await processRequest.post(FRAME_APIS.LOGIN_BASE_HANDSHAKE)
        //进行判断token有效性，再存入token，无效则跳登录页
        next()
    } else {
        //无token，跳转登录页
        next({name: "login"})
        return
    }
})

export default router
